package app;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import entities.Employee;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author yoshi
 */
public class Auth extends Employee {

    public Auth(ResultSet rs) {
        super(rs);
    }

    public static boolean verify(String username, String password) {
        final Connection connection = Global.getConnection();
        PreparedStatement pst = null;
        ResultSet rs = null;
        boolean result = false;

        try {
            pst = connection.prepareStatement("SELECT * FROM employees AS e WHERE e.username = ? AND e.password = ? AND e.active = 1");
            pst.setString(1, username);
            pst.setString(2, Global.hashPassword(password));
            rs = pst.executeQuery();

            if (rs.next()) {
                result = true;
                Global.setAuth(new Auth(rs));
            }
        } catch (SQLException ex) {
            Logger.getLogger(Auth.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                rs.close();
                pst.close();
                connection.close();
            } catch (SQLException ex) {
                Logger.getLogger(Auth.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                return result;
            }
        }
    }

    public static void refreshAuth() {
        Connection connection = Global.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            ps = connection.prepareStatement(Global.getEmployeeQuery() + " WHERE e.id = ? AND e.active = 1");
            ps.setLong(1, Global.getAuth().getId());
            rs = ps.executeQuery();

            if (rs.next()) {
                Global.setAuth(new Auth(rs));
            }
        } catch (SQLException ex) {
            Logger.getLogger(Auth.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                rs.close();
                ps.close();
                connection.close();
            } catch (SQLException ex) {
                Logger.getLogger(Auth.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
